package ptumall.service.impl;


import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import ptumall.config.AiTongueProperties;
import ptumall.service.AccessTokenService;
import ptumall.service.IRestTemplateService;
import ptumall.utils.JsonUtil;
import ptumall.utils.ResultVO;

import java.util.Map;

@Slf4j
@Service
@RequiredArgsConstructor
public class AccessTokenServiceImpl implements AccessTokenService {
    private final AiTongueProperties aiTongueProperties;
    private final IRestTemplateService restTemplateService;

    @Override
    public String getAccessToken() {
        MultiValueMap<String, Object> params = new LinkedMultiValueMap<>();
        params.add("devid", aiTongueProperties.getDevId());
        params.add("devsecret", aiTongueProperties.getDevSecret());
        ResultVO<?> accessTokenResult = restTemplateService.postForObject(aiTongueProperties.getGetTokenUrl(), params, ResultVO.class);
        log.info("access_token result:{}", JsonUtil.toJson(accessTokenResult));
        if (!accessTokenResult.getCode().equals("0")) {
            return null;
        }
        return ((Map<?, ?>) accessTokenResult.getData()).get("access_token").toString();
    }
}
